Page({

    data: {
        hide: true,
        resultMun: '',
        resultTxt: '',
        resColor: 'black'
    },

    formSubmit(event) {
        const {width} = event.detail.value;
        const {height} = event.detail.value;

        if (width === '') return;
        if (height === '') return;
        if (width === '' && height === '') return

        //校验
        if (width > 220 || width < 40) {
            wx.showToast({
                title: '请重新输入正确的体重',
                icon: 'none'
            })
            return;
        }
        //校验
        if (height > 220 || height < 130) {
            wx.showToast({
                title: '请重新输入正确的身高',
                icon: 'none'
            })
            return;
        }

        //计算
        const heightCM = height / 100;
        let bmi = width / (heightCM * heightCM);
        let res = bmi.toFixed(1)

        let resultTxt;
        let resColor;

        //判断
        if (bmi < 18.5) {
            resultTxt = '过低';
            resColor = '#6da2e5'
        } else if (bmi >= 18.5 && bmi < 23.9) {
            resultTxt = '正常';
            resColor = '#3634aa'
        } else if (bmi > 24 && bmi < 27) {
            resultTxt = '过重';
            resColor = '#cd7e61'
        } else if (bmi > 28 && bmi <= 32) {
            resultTxt = '肥胖';
            resColor = '#f8a440'
        } else if (bmi > 32) {
            resultTxt = '非常肥胖';
            resColor = '#b5414f'
        }

        this.setData({
            resultMun: res,
            resultTxt,
            resColor,
            hide: false
        })
        //持久化到本地缓存
        let UserBMI = {
            resultMun: res,
            resultTxt,
            resColor,
        }
        wx.setStorageSync('UserBMI', UserBMI)
    },
    cancel() {
        wx.navigateBack({
            delta: 1
        })
    },
    clearStorage() {
        wx.removeStorageSync('UserBMI')
        this.setData({
            resultMun: '',
            resultTxt: '',
        })
        wx.showToast({
            title: '清除缓存成功！'
        })
        setTimeout(() => {
            this.setData({
                hide: true
            })
        }, 500)

    },
    onLoad(options) {
        wx.showLoading();
        if (wx.getStorageSync('UserBMI')) {
            let UserBMI = wx.getStorageSync('UserBMI');
            this.setData({
                resultMun: UserBMI.resultMun,
                resColor: UserBMI.resColor,
                resultTxt: UserBMI.resultTxt,
                hide: false
            })
        }
        wx.hideLoading();
    },

})